package com.iteaj.iot.simulator;

import com.iteaj.iot.AbstractProtocol;
import com.iteaj.iot.CoreConst;
import com.iteaj.iot.SocketMessage;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.MultiClientManager;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.iot.client.component.TcpClientComponent;
import com.iteaj.iot.simulator.dtu.SimulatorDtuClient;
import com.iteaj.iot.simulator.dtu.SimulatorDtuConnectProperties;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class SimulatorClientComponent extends TcpClientComponent<SimulatorClientMessage> {

    public SimulatorClientComponent() { }

    public SimulatorClientComponent(SimulatorConnectProperties config) {
        super(config);
    }

    public SimulatorClientComponent(SimulatorConnectProperties config, MultiClientManager clientManager) {
        super(config, clientManager);
    }

    @Override
    public TcpSocketClient createNewClient(ClientConnectProperties config) {
        if(config == null) {
            throw new IllegalArgumentException("未指定连接配置");
        }

        if(config instanceof SimulatorDtuConnectProperties) {
            return new SimulatorDtuClient(this, (SimulatorDtuConnectProperties) config);
        }

        throw new IllegalStateException("不支持的模拟器配置["+config.getClass().getSimpleName()+"]");
    }

    @Override
    public SimulatorClientMessage doTcpDecode(ChannelHandlerContext ctx, ByteBuf decode) {
        SimulatorClientMessage socketMessage = (SimulatorClientMessage) super.doTcpDecode(ctx, decode);
        ClientConnectProperties connectProperties = ctx.channel().attr(CoreConst.CLIENT_KEY).get();
        socketMessage.setProperties((SimulatorConnectProperties) connectProperties);
        return socketMessage;
    }

    @Override
    public SocketMessage createMessage(byte[] message) {
        return new SimulatorClientMessage(message);
    }

    @Override
    public String getName() {
        return "设备模拟器";
    }

    @Override
    public String getDesc() {
        return "模拟各种硬件设备(比如：DTU)";
    }

    @Override
    public AbstractProtocol getProtocol(SimulatorClientMessage message) {
        return message.getProperties().getProtocol(message);
    }
}
